import {size} from '@/app/utils';
import React,{useState,useEffect,useContext} from 'react';
import {
  View,
  Text,
  Image,
  TextInput,
  StatusBar,
  Pressable,
} from 'react-native';
import { useTranslation } from '@/app/utils/useTranslation';
import Button from '@/app/components/Button'
import { useNavigation } from "@react-navigation/native";
import {styles} from './style/LoginScreenCss'
import Headers from '@/app/components/header/Headers';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getLogin,getUserInfo } from './serve'
import { useSafeAreaInsets } from 'react-native-safe-area-context';
let LoginScreen = (props:any)=>{
    const insets = useSafeAreaInsets();
    const { t } = useTranslation();
    let [tabIndex,setTabIndex] = useState('0');
    let [phone,setPhone] = useState('');
    let [eye,setEye] = useState(false);
    let [password,setPassword] = useState('');
    let [disabled,setDisabled] = useState(false);
    let navigation = useNavigation<any>();
    let [navBarHeight,setNavBarHeight] = useState(0);

    function handleLogin() {
        // 校验邮箱/手机（当前仅 Email 模式）
        if(!phone){
            return global.$toast(t('t394'));
        }
        if(tabIndex+''=='0'){
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if(!emailRegex.test(phone)){
                return global.$toast(t('t362'));
            }
        }

        // 校验密码 6-16 位，且必须包含字母和数字，仅允许字母数字
        if(!password){
            return global.$toast(t('t395'));
        }
        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9]{6,16}$/;
        if(!passwordRegex.test(password)){
            return global.$toast(t('t382'));
        }
        let params={
            "loginName":phone,
            "password":password
        }
        setDisabled(true);
        getLogin(params).then(async(res:any)=>{
            const token = (res && res.data );
            if(token){
                try {
                    await AsyncStorage.setItem('token', token);
                } catch (_e) {}
            }
            getUserInfo({}).then(async(res:any)=>{
                setDisabled(false);
                let data = res.data||{};
                if(res && res.data){
                    try { 
                        await AsyncStorage.setItem('login', 'true');
                        await AsyncStorage.setItem('userInfo', JSON.stringify(data));
                    } catch (_e) {}
                }
                navigation.reset({
                    index: 0,
                    routes: [{ name: '(tabs)' }],
                });
            }).catch(()=>{
                setDisabled(false);
            })
        }).catch(()=>{
            setDisabled(false);
        })
    }

    function onRegistered(){
        navigation.navigate('pages/auth/RegisteredScreen');
    }

    function onForgetPwd(){
        navigation.navigate('pages/auth/ForgetPasswordScreen');
    }

    function getNavBarHeight(data:any){
        console.log('getNavBarHeight---:',data);
        setNavBarHeight(data)
    }

    useEffect(() => {
        const checkLoginStatus = async () => {
            try {
                const value = await AsyncStorage.getItem('login');
                console.log('checkLoginStatus---:',value);
                if (value === 'true') { // Explicitly convert string to boolean
                    navigation.reset({
                        index: 0,
                        routes: [{ name: '(tabs)' }],
                    });
                }
            } catch (e) {
                console.error('获取登录状态时出错', e);
            }
        };
        
        checkLoginStatus();
    }, []);

    return (
         <View style={{ flex: 1,backgroundColor:"#fff"}}>
            <Headers
                title={''}
                border={false}
                barStyle={0}
                leftTitle={''}
                backgroundColor={'#fff'}
                centerColor={'#666'}
                {...props}
                getNavBarHeight={getNavBarHeight}
                rightContent={
                    <View style={{width:size(80)}}>
                        <Button 
                            onClick={() => {
                                onRegistered();
                            }}
                            disabled={disabled}
                            style={{width:size(80)}}
                         >
                                <Text style={{width:size(80),color:'#38B781',fontSize:size(14),textAlign:'right'}}>{t('t386')}</Text>
                        </Button>
                    </View>
                }
            />
            <KeyboardAwareScrollView style={{flex:1,paddingTop :size(30),flexDirection:'column'}}>
                <View style={{ flex:1}}>
                    <View style={styles.form}>
                        <View style={styles.logobox}>
                            <Image
                                source={
                                    require('@/assets/images/auth/logo2.png')
                                }
                                style={[styles.IconImage]}
                            />
                        </View>
                        <View>
                            <View>
                                <Text style={styles.title}>{t('t371')}</Text>
                            </View>
                            <View>
                                <Text style={styles.subtitle}>{t('t396')}</Text>
                            </View>
                        </View>
                        <View style={styles.tabbox}>
                            <Pressable onPress={()=>{
                                setTabIndex('0');
                                setPhone('');
                            }} style={[styles.tabItem,tabIndex+''=='0'?styles.tabItemActive:null]}>
                                <Text style={[styles.tabtext,tabIndex+''=='0'?styles.tabtextActive:null]}>{t('t366')}</Text>
                            </Pressable>
                            <Pressable onPress={()=>{
                                global.$toast({message:t('t29')})
                            }} style={[styles.tabItem,tabIndex+''=='1'?styles.tabItemActive:null]}>
                                <Text style={[styles.tabtext,tabIndex+''=='1'?styles.tabtextActive:null]}>{t('t367')}</Text>
                            </Pressable>
                        </View>
                        <View style={styles.formItem}>
                            <TextInput
                                readOnly={disabled}
                                value={phone}
                                inputMode={tabIndex+''=='0'?'email':'tel'}
                                onChangeText={(text) => {
                                    setPhone(text)
                                }}
                                keyboardType={'phone-pad'}
                                style={styles.input} placeholder={tabIndex+''=='0'?t('t368'):t('t369')}/>
                        </View>
                        <View style={[styles.formItem, { marginTop: 15 }]}>
                            <TextInput
                                readOnly={disabled}
                                value={password}
                                secureTextEntry={!eye}
                                onChangeText={(text) => {
                                    setPassword(text);
                                }} style={styles.input} placeholder={t('t380')}/>
                                <Pressable onPress={()=>{
                                    setEye(!eye);
                                }}>
                                    <Image style={styles.icon} source={eye?require('@/assets/images/noeye.png'):require('@/assets/images/eye.png')} />
                                </Pressable>
                        </View>
                        <View style={styles.forget} >
                            <Pressable onPress={() => onForgetPwd()}>
                                <Text style={{fontSize:size(14),color:'#38B781' }}>{t('t397')}</Text>
                            </Pressable>
                        </View>
                        <View style={[{ marginTop: 20 }]}>
                            <Button 
                                onClick={() => {
                                    handleLogin();
                                    // global.$lweikaifang() //使用loading
                                }}
                                disabled={disabled}
                                style={styles.login_box_footer_btn}
                            >
                                <Text style={styles.login_box_footer_btn_text}>{t('t371')}</Text>
                            </Button>
                        </View>
                    </View>
                </View>
            </KeyboardAwareScrollView>
            <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center',paddingBottom:size(insets.bottom?insets.bottom:10)}}>
                <Text style={styles.loginBox}>{t('t398')}</Text>
                <Button><Text onPress={()=>{
                    onRegistered();
                }} style={{color:'#38B781'}}>{t('t386')}</Text></Button>
            </View>
        </View>
    )
}

export default LoginScreen;